import { AfterViewInit, Component, ElementRef, Input, ViewChild } from '@angular/core';

import { Chart } from '@antv/g2';
import { ColumnChart } from '@app/core/domain/dashboard';
import { DashboardService } from '@app/core/services/http/dashboard/dashboard.service';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzGridModule } from 'ng-zorro-antd/grid';

@Component({
  selector: 'app-income-chart',
  standalone: true,
  imports: [NzCardModule, NzGridModule],
  templateUrl: './income-chart.component.html',
  styleUrl: './income-chart.component.less'
})
export class IncomeChartComponent implements AfterViewInit {
  @Input() dataType: number = 1;
  incomeData: ColumnChart[] = [];
  @ViewChild('incomeChart') incomeChart!: ElementRef<HTMLElement>;
  constructor(private readonly dashboardService: DashboardService) {}

  initIncome(): void {
    this.incomeChart.nativeElement.innerHTML = '';
    const chart = new Chart({
      container: 'income',
      autoFit: true,
      height: 295,
      padding: [40, 40, 32, 72]
    });
    chart.data(this.incomeData);
    chart.scale('value', {
      nice: true
    });
    chart.axis('type', {
      tickLine: null,
      line: null
    });

    chart.axis('value', {
      label: {
        formatter: val => {
          return +val;
        }
      },
      line: {
        style: { display: 'none', stroke: 'black', lineWidth: 0, lineDash: [4, 5], strokeOpacity: 0.7, shadowColor: 'black', shadowBlur: 10, shadowOffsetX: 5, shadowOffsetY: 5, cursor: 'pointer' }
      },
      grid: {
        closed: true,
        line: {
          style: {
            opacity: 0,
            lineWidth: 0,
            strokeOpacity: 0.7
          }
        }
      }
    });

    chart.tooltip({
      showMarkers: false
    });
    chart.interaction('element-active');
    chart.legend('type', {});
    chart
      .interval()
      .position('type*value')
      .color('detail', ['#2681ff', '#00ff44', '#2611ff', '#26aa99'])
      .adjust([
        {
          type: 'dodge',
          marginRatio: 10 / 32
        }
      ])
      .label('value', {
        offset: 10
      });
    chart.render();
  }

  loadIncomeData(): void {
    this.dashboardService.getIncomeChartData(this.dataType).subscribe(result => {
      this.incomeData = result;
      this.initIncome();
    });
  }

  ngAfterViewInit(): void {
    this.loadIncomeData();
  }
}
